package javacource.redis.service;

import javacource.redis.lock.RedisLock;
import javacource.redis.subscribe.RedisSubscribe;
import javacource.redis.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 * Create by chenhd on 2021/10/23.
 */
@Service
public class DealService {

    @Autowired
    RedisOperator redisOperator;

    @Autowired
    RedisSubscribe redisSubscribe;

    @Autowired
    @Qualifier("redisLock")
    RedisLock redisLock;

    /**
     * 减库存操作+减库存后续异步操作
     *
     * @param itemId 商品id
     */
    public void decrease(String itemId) {
        if (!redisLock.lock("lock", itemId, 20)) {
            return;
        }
        System.out.println("拿到分布式锁" + itemId);
        try {
            String itemCount = redisOperator.get(itemId);
            if (itemCount == null) {
                System.out.println(itemId + "商品不存在.");
                return;
            }

            int count = Integer.parseInt(itemCount);
            System.out.println("当前库存" + count);
            if (count <= 0) {
                System.out.println("库存不足，减库存失败.");
                return;
            }

            boolean result = redisOperator.decr(itemId);
            if (result) {
                System.out.println("减库存成功.");
            } else {
                System.out.println("减库存失败.");
                return;
            }
            //发送消息异步处理
            System.out.println("开始发送异步消息.");
            redisOperator.pub("decreaseMessage", itemId);

        } catch (Exception e) {
            //log
            e.printStackTrace();
        } finally {
            redisLock.unLock("lock", itemId);
            System.out.println("释放分布式锁" + itemId);
        }
    }
}
